package com.contactbook.web.server.dto;

import java.util.HashSet;

import java.util.Set;

import com.contactbook.web.client.dto.ContactDTO;
import com.contactbook.web.client.dto.GroupDTO;

import contactbook.model.Contact;
import contactbook.model.Group;

public class GroupDTOConverter {

private static final long serialVersionUID = 1L;
	
	public static GroupDTO convert(Group group, boolean referenced) {
		
		GroupDTO groupDTO = new GroupDTO(group.getName(), group.getDescription());
		
		groupDTO.setId(group.getId());
		
		if (referenced == true) {
			groupDTO.setAccount(AccountDTOConverter.convert(group.getAccount(), false));
		
			Set<Contact> contacts = group.getContacts();
			Set<ContactDTO> contactDTOs = new HashSet<ContactDTO>(contacts.size());
			if (contacts != null) {
				for (Contact contact : contacts) {
					contactDTOs.add(ContactDTOConverter.convert(contact, false));
				}
			}
			groupDTO.setContacts(contactDTOs);
		}
		
		return groupDTO;
	}
	
	public static Group convertDTO(GroupDTO groupDTO, boolean referenced) {
		Group group = new Group();
		
		group.setId(groupDTO.getId());
		group.setName(groupDTO.getName());
		group.setDescription(groupDTO.getDescription());
		
		if (referenced == true) {
			group.setAccount(AccountDTOConverter.convertDTO(groupDTO.getAccount(), false));
		
			Set<ContactDTO> contactsDTO = groupDTO.getContacts();
			Set<Contact> contacts = new HashSet<Contact>(contactsDTO.size());
			if (!contactsDTO.isEmpty()) {
				for (ContactDTO contact : contactsDTO) {
					contacts.add(ContactDTOConverter.convertDTO(contact, false));
				}
			}
			group.setContacts(contacts);
		}
					
		return group;
	}
}
